package io.gitee.zhucan123.core.infrastructure.exception.advice;


import com.niimbot.middlend.core.infrastructure.exception.InvalidOperationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;


/**
 * @program: homo
 * @description: 参数不合法异常
 * @author: zhuCan
 * @date: 2019-05-21 14:15
 **/
@RestControllerAdvice
@Slf4j
public class ValidExceptionAdvice {

  @ExceptionHandler(BindException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public ErrorDTO handleBindException(HttpServletRequest req, BindException ex) {
    FieldError fieldError = ex.getBindingResult().getFieldError();
    String errorMessage = fieldError.getField() + fieldError.getDefaultMessage();
    String errorURL = req.getRequestURL().toString();
    return new ErrorDTO(errorMessage, HttpStatus.BAD_REQUEST.value(), errorURL);
  }

  @ExceptionHandler(InvalidOperationException.class)
  @ResponseStatus(HttpStatus.EXPECTATION_FAILED)
  public ErrorDTO handlerInvalidOperationException(HttpServletRequest req, InvalidOperationException e) {
    String errorURL = req.getRequestURL().toString();
    return new ErrorDTO(e.getMessage(), HttpStatus.EXPECTATION_FAILED.value(), errorURL);
  }

}
